/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-11-12 15:23:10
 ******************************************************************************/
package cn.com.xy.sms.sdk.net.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import cn.com.xy.sms.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.entity.CenterNumLocationInfo;
import cn.com.xy.sms.sdk.db.entity.IccidInfo;
import cn.com.xy.sms.sdk.db.entity.IccidInfoManager;
import cn.com.xy.sms.sdk.db.entity.JarSubInfo;
import cn.com.xy.sms.sdk.db.entity.JarSubInfoManager;
import cn.com.xy.sms.sdk.db.entity.PhoneNumServe;
import cn.com.xy.sms.sdk.db.entity.SceneRule;
import cn.com.xy.sms.sdk.db.entity.Sceneconfig;
import cn.com.xy.sms.sdk.db.entity.SmsParseRecorder;
import cn.com.xy.sms.sdk.db.entity.SysParamEntityManager;
import cn.com.xy.sms.sdk.db.entity.UpdateTaskManager;
import cn.com.xy.sms.sdk.db.entity.pubinfo.NumName;
import cn.com.xy.sms.sdk.db.entity.pubinfo.NumNameManager;
import cn.com.xy.sms.sdk.db.entity.pubinfo.PubInfoManager;
import cn.com.xy.sms.sdk.dex.DexUtil;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.net.NewXyHttpRunnable;
import cn.com.xy.sms.sdk.net.XyHttpRunnable;
import cn.com.xy.sms.sdk.util.JsonUtil;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.sdk.util.XmlManager;

/* SDK-397 huangzhiqiang 20160524 start */
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/* SDK-397 huangzhiqiang 20160524 end */

/* SDK-421 huangzhiqiang 20160525 start */
import cn.com.xy.sms.sdk.service.pubInfo.PubInfoNetService;
import cn.com.xy.sms.sdk.db.entity.pubinfo.ShardData;
import cn.com.xy.sms.sdk.db.entity.pubinfo.ShardDataManager;
import cn.com.xy.sms.sdk.db.entity.pubinfo.ShardDataManager.RequestStatus;
/* SDK-421 huangzhiqiang 20160525 end */
/*SDK-525 hewengao 20160707 start*/
import android.telephony.TelephonyManager;
import android.content.Context;
import cn.com.xy.sms.sdk.util.DuoquUtils;
/*SDK-525 hewengao 20160707 end*/

/* SDK-616 hewengao 20160918 start */
import cn.com.xy.sms.sdk.threadpool.SmartSmsThreadPoolManager;
/* SDK-616 hewengao 20160918 end */
public class ServerUtil {

    /* SDK-397 huangzhiqiang 20160524 start */
//    private static final ExecutorService NUM_INFO_UPLOAD_POOL = Executors.newSingleThreadExecutor();
    public static final String NUM_TYPE_PHONE = "1"; // 电话号码
    public static final String NUM_TYPE_UNDEFINED = "2"; // 未定义
    public static final String NUM_TYPE_PUBID = "3"; // 公众号ID
    private static final int NAME_TYPE_UNKNOWN = -1; // 名称类型-未知
    /* SDK-397 huangzhiqiang 20160524 end */

    public static StringBuffer getStringBuffer() {
        StringBuffer sb = new StringBuffer(
                "<?xml version='1.0' encoding='utf-8'?>");
        return sb;
    }

    /******
     * 
     * 0：查询iccid信息 1 :上传iccid信息
     * *******/
    public static String getQueryIccidInfoRequest(IccidInfo info, int cmd) {
        try {
            /* SDK-504 huangzhiqiang 20160623 start */
            StringBuffer sb = getStringBuffer();
            /* SDK-504 huangzhiqiang 20160623 end */
            sb.append("<queryIccidInfoRequest>");
            sb.append("<iccid>");
            sb.append(info.iccid);
            sb.append("</iccid>");
            sb.append("<cmd>" + cmd + "</cmd>");
            sb.append("<operator>" + info.operator + "</operator>");
            sb.append("<provinces>" + info.provinces + "</provinces>");
            sb.append("<city>" + info.city + "</city>");
            sb.append("<updateTime>" + info.updateTime + "</updateTime>");
            sb.append("</queryIccidInfoRequest>");
            /* SDK-504 huangzhiqiang 20160623 start */
            return sb.toString();
            /* SDK-504 huangzhiqiang 20160623 end */
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "ServerUtil getQueryIccidInfoRequest: ", e);
        }
        /* SDK-504 huangzhiqiang 20160623 start */
        return null;
        /* SDK-504 huangzhiqiang 20160623 end */
    }

    public static String getUpdateJarsRequest(List<JarSubInfo> jarSubInfoList,
            Map<String, String> actionRecord, String emVer) {
        StringBuffer jarNames = new StringBuffer();
        StringBuffer jarVersions = new StringBuffer();
        JarSubInfo info = null;
         
        try {
            for (int i = 0; i < jarSubInfoList.size(); i++) {
                info = jarSubInfoList.get(i);
                /* SDK-579 huangzhiqiang 20160805 start */
                if (i > 0) {
                    jarNames.append(",");
                    jarVersions.append(",");
                }
                /* SDK-579 huangzhiqiang 20160805 end */
                jarNames.append(info.name);
                String key = info.name;
                // 根据情景号获取对应的服务数据
                if (key.startsWith("PU")) {
                    key = key.replace("PU", "");
                }

                String record = actionRecord.get(key);
                if (!StringUtils.isNull(record)) {
                    jarNames.append(record);
                }
                jarVersions.append(info.version);
                JarSubInfoManager.updateTime(info.name);
            }
            /* SDK-504 huangzhiqiang 20160623 start */
            StringBuffer sb = getStringBuffer();
            /* SDK-504 huangzhiqiang 20160623 end */
            sb.append("<UpdateRecognitionJarRequest>");
            sb.append("<reqVersion>");
            sb.append(DexUtil.getSuanfaVersion());
            sb.append("</reqVersion>");

            sb.append("<jarVersion>");
            sb.append(jarVersions.toString());
            sb.append("</jarVersion>");

            sb.append("<jarname>");
            sb.append(jarNames.toString());
            sb.append("</jarname>");

            sb.append("<emVer>");
            sb.append(emVer);
            sb.append("</emVer>");

            sb.append("</UpdateRecognitionJarRequest>");
            /* SDK-504 huangzhiqiang 20160623 start */
            return sb.toString();
            /* SDK-504 huangzhiqiang 20160623 end */
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "ServerUtil getUpdateJarsRequest: ", e);
        }
        /* SDK-504 huangzhiqiang 20160623 start */
        return null;
        /* SDK-504 huangzhiqiang 20160623 end */
    }

    public static String getUpdatePublicInfoRequest(String version, String jarName, int status, int count) {
        /* SDK-504 huangzhiqiang 20160623 start */
        StringBuffer sb = getStringBuffer();
        sb.append("<UpdatePublicInfoRequest>");
        sb.append("<PublicInfoVersion>");
        sb.append(version);
        sb.append("</PublicInfoVersion>");
        sb.append("<status>");
        sb.append(status);
        sb.append("</status>");
        sb.append("<count>");
        sb.append(count);
        sb.append("</count>");
        sb.append("</UpdatePublicInfoRequest>");
        return sb.toString();
        /* SDK-504 huangzhiqiang 20160623 end */
    }

    public static String QueryOperatorRequest(String phoneNum, String simIccid,
            Map extend){
    	try {
    		JSONObject json = new JSONObject();
        	json.put("phone", phoneNum);
        	json.put("iccid", simIccid);
        	if(extend!=null && !extend.isEmpty()){
            	json.put("cnum", extend.get("cnum"));
            	/* SDK-626 zhaojiangwei 20160929 start*/
                json.put("operator", extend.get("operator"));
                json.put("province", extend.get("province"));
                /* SDK-626 zhaojiangwei 20160929 end*/
        	}
        	return json.toString();
		} catch (Exception e) {
		    LogManager.e(Constant.TAG, "ServerUtil QueryOperatorRequest: ", e);
		}
    	return "";
    
    }
    public static String QueryOperatorMsgRequest(String phoneNum, String msg,
            Map extend){
    	try {
    		JSONObject json = new JSONObject();
        	json.put("phone", phoneNum);
        	json.put("msg", msg);
        	if(extend!=null && !extend.isEmpty()){
            	json.put("cnum", extend.get("cnum"));
        	}
        	return json.toString();
		} catch (Exception e) {
            LogManager.e(Constant.TAG, "ServerUtil QueryOperatorMsgRequest: ", e);
		}
    	return "";
    
    }

    /**
     * 描述：旧接口 报文构造
     * 
     * @param num
     * @param cnum
     * @param areaCode
     * @param iccid
     * @param type （1：电话号码，2：未定义 3：公众号ID ）
     * @return
     * @return String
     */
    public static String QueryPubInfoRequest(String num, String cnum,
            String areaCode, String iccid, String type) {
        /* SDK-397 huangzhiqiang 20160524 start */
        NumName numInfo = NumNameManager.getNumNameByNum(StringUtils
                .getPhoneNumberNo86(num));
        String centerNum = numInfo == null ? "" : numInfo.cnum;
        /* SDK-397 huangzhiqiang 20160524 end */

        try {
            /* SDK-504 huangzhiqiang 20160623 start */
            StringBuffer sb = getStringBuffer();
            /* SDK-504 huangzhiqiang 20160623 end */
            sb.append("<QueryPubInfoRequest>");
            sb.append("<cnum>");
            sb.append(cnum == null ? centerNum : cnum);
            sb.append("</cnum>");
            sb.append("<areaCode>" + areaCode + "</areaCode>");
            sb.append("<iccid>" + iccid + "</iccid>");
            sb.append("<type>" + type + "</type>");

            /* SDK-397 huangzhiqiang 20160524 start */
            StringBuffer sbrNumAttribute = new StringBuffer();
            // num类型为手机号码时才构造额外的上报报文(加密签名、退订指令)
            if (NUM_TYPE_PHONE.equals(type)) {
                if (numInfo != null) {
                    boolean needUploadName = numInfo.markTime == 1; // markTime为1时代表需要上传加密签名
                    if (needUploadName && !StringUtils.isNull(numInfo.name)) {
                        sb.append("<sign>");
                        // 加密签名
                        sb.append(getSha256EncodeSafeName(numInfo.name));
                        sb.append("</sign>");

                        int nameType = PubInfoManager.getNameType(numInfo.num, areaCode);
                        if (nameType != NAME_TYPE_UNKNOWN) {
                            // 名称类型(0:企业名称 1:签名)
                            sbrNumAttribute.append(" f=\"").append(nameType).append("\" ");
                        }
                    }

                    boolean needUploadCmd = numInfo.markCmd == 1; // markCmd为1时代表需要上传退订指令
                    if (needUploadCmd && !StringUtils.isNull(numInfo.cmd)) {
                        // 退订指令
                        String numSignMessage = createNumSignMessage(num, numInfo.cmd);
                        if (!StringUtils.isNull(numSignMessage)) {
                            sb.append("<unSubscribe>");
                            sb.append(numSignMessage);
                            sb.append("</unSubscribe>");
                        }
                    }
                    /* SDK-478 huangzhiqiang 20160628 start */
                    boolean needUploadEC = numInfo.markEC == 1; // markEC为1时代表需要上传行业编码
                    if (needUploadEC && !StringUtils.isNull(numInfo.ec)) {
                        // 行业编码
                        sb.append("<ec>");
                        sb.append(numInfo.ec);
                        sb.append("</ec>");
                    }

                    if (needUploadName || needUploadCmd || needUploadEC) {
                        // 更新签名、退订指令、行业编码上传标志为0(0代表不需要上传)
                        NumNameManager.updateMarkByNum(numInfo.num, 0, 0);
                    }
                    /* SDK-478 huangzhiqiang 20160628 end */
                }

                /* SDK-421 huangzhiqiang 20160525 start */
                // 每个号码读取前10条原文签名数据
                String shardUploadMessage = createShardSignMessage(num, 10);
                if (!StringUtils.isNull(shardUploadMessage)) {
                    // 添加原文签名数据报文内容
                    sb.append("<shard>");
                    sb.append(shardUploadMessage);
                    sb.append("</shard>");
                }
                /* SDK-421 huangzhiqiang 20160525 end */
            }
            sb.append("<num");
            if (sbrNumAttribute.length() > 0) {
                // 添加名称类型属性
                sb.append(sbrNumAttribute);
            }
            sb.append(">");
            sb.append(num);
            sb.append("</num>");
            /* SDK-397 huangzhiqiang 20160524 end */
            sb.append("</QueryPubInfoRequest>");
            /* SDK-504 huangzhiqiang 20160623 start */
            return sb.toString();
            /* SDK-504 huangzhiqiang 20160623 end */
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "ServerUtil QueryPubInfoRequest: ", e);
        }
        /* SDK-504 huangzhiqiang 20160623 start */
        return null;
        /* SDK-504 huangzhiqiang 20160623 end */
    }

    /* SDK-421 huangzhiqiang 20160525 start */
    /**
     * 生成分片签名数据报文
     * 
     * @param num
     * @param limit
     * @return
     */
    public static String createShardSignMessage(String num, int limit) {
        if (StringUtils.isNull(num) || limit < 1) {
            return null;
        }
        List<ShardData> shardDatas = ShardDataManager.queryShardDataByNum(num, RequestStatus.STATUS_NOT_REQUEST, limit);
        if (shardDatas == null || shardDatas.isEmpty()) {
            return null;
        }
        try {
            List<String> contentSigns = new ArrayList<String>();
            StringBuilder sbrSigns = new StringBuilder();
            int size = shardDatas.size();
            for (int i = 0; i < size; i++) {
                if (i > 0) {
                    sbrSigns.append(";");
                }
                String contentSign = shardDatas.get(i).contentSign;
                sbrSigns.append(contentSign);
                contentSigns.add(contentSign);
            }

            // 读取分片数据后更新对应分片数据的请求状态为1(已请求)
            ShardDataManager.updateStatusByContentSign(contentSigns, ShardDataManager.RequestStatus.STATUS_HAS_REQUEST);

            StringBuilder sbrShardSign = new StringBuilder();
            sbrShardSign.append("<shardSign sign=\"").append(sbrSigns).append("\">");
            sbrShardSign.append(num);
            sbrShardSign.append("</shardSign>");
            return sbrShardSign.toString();
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "ServerUtil createShardSignMessage: ", e);
        }
        return null;
    }

    /**
     * 生成分片签名数据报文
     * 
     * @return
     */
    public static String createShardSignMessage(List<String> nums, int limit) {
        if (nums == null || nums.isEmpty()) {
            return null;
        }

        StringBuilder sbrShardSigns = new StringBuilder();
        for (String num : nums) {
            String shardSign = createShardSignMessage(num, limit);
            if (!StringUtils.isNull(shardSign)) {
                sbrShardSigns.append(shardSign);
            }
        }
        return sbrShardSigns.toString();
    }
    /* SDK-421 huangzhiqiang 20160525 end */

    /**
     * 描述：批量查询企业号资料请求 报文构造
     * 
     * <allNums> <num ver=”22”>1061111</num> <num ver=”33”>1062222</num>
     * </allNums>
     * 
     * @param num
     * @param cnum
     * @param areaCode
     * @param iccid
     * @param type （1：电话号码，2：未定义 3：公众号ID ）
     * @return
     * @return String
     */
    public static String QueryPubInfoWithListReqBody(List<String> list,
            String cnum, String areaCode, String iccid, String type) {
        try {
            if (list == null || list.isEmpty()) {
                return null;
            }
            /* SDK-504 huangzhiqiang 20160623 start */
            StringBuffer sb = getStringBuffer();
            /* SDK-504 huangzhiqiang 20160623 end */
            sb.append("<QueryPubInfoRequest>");
            sb.append("<areaCode>" + areaCode + "</areaCode>");
            sb.append("<iccid>" + iccid + "</iccid>");
            sb.append("<type>" + type + "</type>");

            /* SDK-384 huangzhiqiang 20160411 start */
            List<JSONObject> jsonObjectList = new ArrayList<JSONObject>();
            List<String> phoneNumList = new ArrayList<String>();
            List<String> tempCheckDuplicateList = new ArrayList<String>();
            for (String jsonStr : list) {
                if (tempCheckDuplicateList.contains(jsonStr)) {
                    continue;
                }
                tempCheckDuplicateList.add(jsonStr);
                JSONObject jsonObject = new JSONObject(jsonStr);
                jsonObjectList.add(jsonObject);
                phoneNumList.add(jsonObject.optString("num")); // (type为1num=电话号码   type为2num=未定义   type为3num=公众号ID）
            }
            /* SDK-384 huangzhiqiang 20160411 end */

            Map<String, Map<String, StringBuilder>> dataList = null;

            /* SDK-397 huangzhiqiang 20160524 start */
            // 号码类型为手机号码
            if (NUM_TYPE_PHONE.equals(type)) {
                // 查询解析识别数据
                dataList = SmsParseRecorder.getParseSmsRecordByPhoneNum(phoneNumList);

                /* SDK-421 huangzhiqiang 20160525 start */
                // 每个号码读取前5条原文签名数据
                String shardUploadMessage = createShardSignMessage(phoneNumList, 5);
                if (!StringUtils.isNull(shardUploadMessage)) {
                    // 添加原文签名数据报文内容
                    sb.append("<shard>");
                    sb.append(shardUploadMessage);
                    sb.append("</shard>");
                }
                /* SDK-421 huangzhiqiang 20160525 end */
            }
            
            /* SDK-378 huangzhiqiang 20160331 begin */
            StringBuffer sbrNum = new StringBuffer();
            StringBuffer sbrNumSign = new StringBuffer();
            List<String> needUpdateNumNameInfoList = new ArrayList<String>();
            boolean numNamePower =  NumNameManager.numNamePower(); // 是否有上传签名的权限(true:有权限  false:无权限)
            for (JSONObject numInfoJson : jsonObjectList) {
                String num = numInfoJson.optString("num"); // (type为1num=电话号码   type为2num=未定义   type为3num=公众号ID）
                String name = numInfoJson.optString("name"); // 企业签名
                String cmd = numInfoJson.optString("cmd"); // 退订指令
                /* SDK-478 huangzhiqiang 20160628 start */
                String ec = numInfoJson.optString("ec"); // 行业编码
                /* SDK-478 huangzhiqiang 20160628 end */
                int nameType = numInfoJson.optInt("nameType", NAME_TYPE_UNKNOWN); // 名称类型(0:企业名称  1:签名)
                int markTime = numInfoJson.optInt("markTime"); // 是否需要上传签名(0:不需要   1:需要)
                int markCmd = numInfoJson.optInt("markCmd"); // 是否需要上传退订指令(0:不需要   1:需要)
                /* SDK-478 huangzhiqiang 20160628 start */
                int markEC = numInfoJson.optInt("markEC"); // 是否需要上传行业编码(0:不需要   1:需要)
                /* SDK-478 huangzhiqiang 20160628 end */
                if (StringUtils.isNull(num)) {
                    continue;
                }

                StringBuffer sbrNumAttribute = null;
                // 号码类型为手机号码时才构造额外的上报报文(加密签名、解析识别数据、退订指令)
                if (NUM_TYPE_PHONE.equals(type)) {
                    sbrNumAttribute = new StringBuffer();
                    /* SDK-721 songzhirong 20170117 start */
                    boolean needUploadName = !StringUtils.isNull(name); 
                    if (numNamePower && needUploadName) {
                    /* SDK-721 songzhirong 20170117 end */
                        // 加密签名
                        sbrNumAttribute.append("\" sign=\"").append(getSha256EncodeSafeName(name));
                        if (nameType != NAME_TYPE_UNKNOWN) {
                            // 名称类型
                            sbrNumAttribute.append("\" f=\"").append(nameType);
                        }
                    }

                    // 解析识别数据
                    Map<String, StringBuilder> data = dataList == null ? null : dataList.get(num);
                    if (data != null && !data.isEmpty()) {
                        sbrNumAttribute.append("\" ac=\"").append(data.get("ac"));
                        sbrNumAttribute.append("\" rc=\"").append(data.get("rc"));
                        sbrNumAttribute.append("\" dt=\"").append(data.get("dt"));
                    }

                    boolean needUploadCmd = markCmd == 1; // markCmd为1时代表需要上传退订指令
                    if (needUploadCmd && !StringUtils.isNull(cmd)) {
                        // 退订指令
                        String numSignMessage = createNumSignMessage(num, cmd);
                        if (!StringUtils.isNull(numSignMessage)) {
                            sbrNumSign.append(numSignMessage);
                        }
                    }

                    /* SDK-478 huangzhiqiang 20160628 start */
                    boolean needUploadEC = markEC == 1; // markEC为1时代表需要上传行业编码
                    if (needUploadEC && !StringUtils.isNull(ec)) {
                        sbrNumAttribute.append("\" ec=\"").append(ec);
                    }
                    /* SDK-478 huangzhiqiang 20160628 end */

                    if (needUploadName || needUploadCmd || needUploadEC) {
                        // 记录上传签名或退订指令的号码，后面批量更新这些号码的最后查询时间及上传标志
                        needUpdateNumNameInfoList.add(num);
                    }
                }

                sbrNum.append("<num ver=\"").append(numInfoJson.optString("version"));
                if (sbrNumAttribute !=null && sbrNumAttribute.length() > 0) {
                    // 添加加密签名、名称类型、解析识别数据属性
                    sbrNum.append(sbrNumAttribute);
                }
                sbrNum.append("\" >");
                sbrNum.append(num);
                sbrNum.append("</num>");
            }

            if (sbrNum.length() > 0) {
                sb.append("<allNums>");
                sb.append(sbrNum);
                sb.append("</allNums>");
            }
            /* SDK-397 huangzhiqiang 20160524 end */

            // 添加退订指令报文
            if (sbrNumSign.length() > 0) {
                sb.append("<unSubscribe>");
                sb.append(sbrNumSign);
                sb.append("</unSubscribe>");
            }
            /* SDK-378 huangzhiqiang 20160331 end */

            sb.append("</QueryPubInfoRequest>");

            /* SDK-397 huangzhiqiang 20160524 start */
            if (needUpdateNumNameInfoList.size() > 0) {
                // 更新签名、退订指令、行业编码上传标志为0(0代表不需要上传)
                NumNameManager.updateMarkByNum(needUpdateNumNameInfoList, 0, 0);
            }
            /* SDK-397 huangzhiqiang 20160524 end */
            /* SDK-504 huangzhiqiang 20160623 start */
            return sb.toString();
            /* SDK-504 huangzhiqiang 20160623 end */
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "ServerUtil QueryPubInfoWithListReqBody: ", e);
        }
        /* SDK-504 huangzhiqiang 20160623 start */
        return null;
        /* SDK-504 huangzhiqiang 20160623 end */
    }

    public static String QueryPubInfoRequest2(String pubId, String version,
            String areaCode, String iccid) {
        StringBuffer sb = getStringBuffer();
        /* SDK-504 huangzhiqiang 20160623 start */
        // try {
        /* SDK-504 huangzhiqiang 20160623 end */
        sb.append("<QueryPubInfoRequest>");
        sb.append("<pubId>");
        sb.append(pubId);
        sb.append("</pubId>");
        sb.append("<version>" + version + "</version>");
        sb.append("<areaCode>" + areaCode + "</areaCode>");
        sb.append("<iccid>" + iccid + "</iccid>");
        sb.append("</QueryPubInfoRequest>");
        /* SDK-504 huangzhiqiang 20160623 start */
        // } catch (Throwable e) {
        // LogManager.e(Constant.TAG, "ServerUtil QueryPubInfoRequest2: " +
        // e.getMessage(), e);
        // }
        /* SDK-504 huangzhiqiang 20160623 end */
        return sb.toString();
    }

    public static String QueryMenuInfoRequest(String pubId, String version,
            String areaCode, String iccid) {
        StringBuffer sb = getStringBuffer();
        /* SDK-504 huangzhiqiang 20160623 start */
        // try {
        /* SDK-504 huangzhiqiang 20160623 end */
        sb.append("<QueryMenuInfoRequest>");
        sb.append("<pubId>");
        sb.append(pubId);
        sb.append("</pubId>");
        sb.append("<version>" + version + "</version>");
        sb.append("<areaCode>" + areaCode + "</areaCode>");
        sb.append("<iccid>" + iccid + "</iccid>");

        sb.append("</QueryMenuInfoRequest>");
        /* SDK-504 huangzhiqiang 20160623 start */
        // } catch (Throwable e) {
        // LogManager.e(Constant.TAG, "ServerUtil QueryMenuInfoRequest: " +
        // e.getMessage(), e);
        // }
        /* SDK-504 huangzhiqiang 20160623 end */
        return sb.toString();
    }
    /*SDK-525 hewengao 20160707 start*/
    private static String getMid(String iccid) {
        try {
            final String ICCID = "iccid";
            final String MID = "mid";
            JSONObject tm0 = DuoquUtils.getSdkDoAction().getTelephonyInfoBySimIndex(0);
            JSONObject tm1 = DuoquUtils.getSdkDoAction().getTelephonyInfoBySimIndex(1);
            String iccid0 = null;
            String iccid1 = null;
            String mid0 = null;
            String mid1 = null;
            if (tm0 != null) {
                iccid0 = tm0.optString(ICCID);
                mid0 = tm0.optString(MID);
            }
            if (tm1 != null) {
                iccid1 = tm1.optString(ICCID);
                mid1 = tm1.optString(MID);
            }
            if (!StringUtils.isNull(iccid)) {
                if (iccid.equals(iccid0) && !StringUtils.isNull(mid0)) {
                    return mid0;
                }
                if (iccid.equals(iccid1) && !StringUtils.isNull(mid1)) {
                    return mid1;
                }
            }
            if (!StringUtils.isNull(mid0)) {
                return mid0;
            }
            if (!StringUtils.isNull(mid1)) {
                return mid1;
            }
            TelephonyManager tm = (TelephonyManager) Constant.getContext().getSystemService(Context.TELEPHONY_SERVICE);
            return tm.getSubscriberId();
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "ServerUtil getMid error:", e);
        }
        return "";
    }
    /*SDK-525 hewengao 20160707 end*/
    public static String QueryLocationRequest(String cNum, String iccid,
            String num) {
        StringBuffer sb = getStringBuffer();
        /* SDK-504 huangzhiqiang 20160623 start */
        // try {
        /* SDK-504 huangzhiqiang 20160623 end */
        /*SDK-525 hewengao 20160707 start*/
        String mid = getMid(iccid);
        if(mid == null){
        	mid = "";
        }
        /*SDK-525 hewengao 20160707 end*/
        sb.append("<QueryLocationRequest>");
        sb.append("<cNum>");
        sb.append(cNum);
        sb.append("</cNum>");
        sb.append("<iccid>" + iccid + "</iccid>");
        sb.append("<num>" + num + "</num>");
        /*SDK-525 hewengao 20160707 start*/
        sb.append("<mid>"+mid+"</mid>");
        /*SDK-525 hewengao 20160707 end*/
        sb.append("</QueryLocationRequest>");
        /* SDK-504 huangzhiqiang 20160623 start */
        // } catch (Throwable e) {
        // LogManager.e(Constant.TAG, "ServerUtil QueryLocationRequest: " +
        // e.getMessage(), e);
        // }
        /* SDK-504 huangzhiqiang 20160623 end */
        return sb.toString();
    }

    public static String QueryTokenRequest(String iccid) {
        StringBuffer sb = getStringBuffer();
        /* SDK-504 huangzhiqiang 20160623 start */
        // try {
        /* SDK-504 huangzhiqiang 20160623 end */
        sb.append("<QueryToken>");
        sb.append("<sdkVersion>");
        sb.append(DexUtil.getSceneVersion());
        sb.append("</sdkVersion>");
        sb.append("<iccid>" + iccid + "</iccid>");
        sb.append("</QueryToken>");
        /* SDK-504 huangzhiqiang 20160623 start */
        // } catch (Throwable e) {
        // LogManager.e(Constant.TAG, "ServerUtil QueryTokenRequest: " +
        // e.getMessage(), e);
        // }
        /* SDK-504 huangzhiqiang 20160623 end */
        return sb.toString();
    }

    public static String QueryNewTokenRequest() {
        try {
            JSONObject json = new JSONObject();
			/*SDK-683 zhaojiangwei 20161121 start */
            json.put("secdata", XyHttpRunnable.appKey + "_" + System.currentTimeMillis());
			/*SDK-683 zhaojiangwei 20161121 end */
            return json.toString();
        } catch (Exception e) {
            LogManager.e(Constant.TAG, "ServerUtil QueryNewTokenRequest: ", e);
        }
        return "";
    }

    public static final String CODE_SUCCESS = "0";
    public static final String CODE_TOKENOUT = "1";
    public static final String CODE_ERROR = "-1";

    public static int success = 0;
    public static int tokenOut = 1;
    public static int error = -1;

    public static Map<String, JSONObject> parsePubInfoRespose(String xml) {
        if (StringUtils.isNull(xml)) {
            return null;
        }
        int resultCode = ServerUtil.error;
        Map<String, JSONObject> infoMap = new HashMap<String, JSONObject>();
        try {
            Document doc = StringUtils.stringConvertXML(xml, "");
            if (doc == null)
                return null;
            Element root = doc.getDocumentElement();

            resultCode = XmlManager.getIntContent(XmlManager.getContentByTag(
                    root, "rstCode"));

            if (resultCode == ServerUtil.error) {
                return null;
            }

            infoMap = generateInfo(doc);
            generateNumList(infoMap, doc);
            generateMenuList(infoMap, doc);
            parseNumSignTask(root);
            parseCMDTask(root);
            /* SDK-421 huangzhiqiang 20160525 start */
            parseShardTask(root);
            /* SDK-421 huangzhiqiang 20160525 end */
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "ServerUtil parsePubInfoRespose: ", e);
            return null;
        }
        return infoMap;

    }

    /* SDK-397 huangzhiqiang 20160524 start */
    /**
     * 解析报文中需要上传的公众号签名，添加上传任务
     * 
     * @param root
     */
    private static void parseNumSignTask(Element root) {
        parseUploadTask(root, "rstSign", UpdateTaskManager.TaskGroup.UPLOAD_PUBINFO_SIGN, 0);
    }

    /**
     * 解析报文中需要上传的退订指令，添加上传任务
     * 
     * @param root
     */
    private static void parseCMDTask(Element root) {
        parseUploadTask(root, "subSign", UpdateTaskManager.TaskGroup.UPLOAD_PUBINFO_CMD, 0);
    }

    /**
     * 解析报文，添加上传任务
     * 
     * @param root
     * @param key 包含上传任务信息的key
     * @param taskGroup
     * @param version
     */
    private static void parseUploadTask(Element root, String key, final UpdateTaskManager.TaskGroup taskGroup,
            final int version) {
        try {
            if (root == null || StringUtils.isNull(key)) {
                return;
            }

            NodeList list = root.getElementsByTagName(key);
            if (list == null || list.getLength() == 0) {
                return;
            }

            final String uploadContent = XmlManager.getTextContent(list.item(0));
            if (StringUtils.isNull(uploadContent)) {
                return;
            }

            // 上传任务入库
            addTask(taskGroup, uploadContent, version);
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "ServerUtil parseUploadTask taskGroup error:",
                    e);
        }
    }

    /* SDK-421 huangzhiqiang 20160525 start */
    /**
     * 解析报文中需要上传的分片指令，添加上传任务
     * 
     * @param root
     */
    private static void parseShardTask(Element root) {
        try {
            if (root == null) {
                return;
            }

            NodeList list = root.getElementsByTagName("shaSign");
            if (list == null || list.getLength() == 0) {
                return;
            }

            Node shaSignNode = list.item(0);
            final NodeList signNodeList = shaSignNode.getChildNodes();
            if (signNodeList == null || signNodeList.getLength() == 0) {
                return;
            }
            /*SDK-616 hewengao 20160912 start*/
//            SmartSmsThreadPoolManager.NUM_INFO_UPLOAD_POOL
            SmartSmsThreadPoolManager.mUploadPubInfoPool.execute(new Runnable() {
            /*SDK-616 hewengao 20160912 end*/
                @Override
                public void run() {
                    try {
                        int length = signNodeList.getLength();
                        JSONArray uploadContentArr = new JSONArray();
                        for (int i = 0; i < length; i++) {
                            try {
                                Element signNode = (Element) signNodeList.item(i);
                                String contentSign = signNode.getFirstChild().getNodeValue();
                                String index = signNode.getAttribute("attr1");
                                String mod = signNode.getAttribute("attr2");
                                // 其中一个值为空则代表为异常数据，不添加任务
                                if (!StringUtils.allValuesIsNotNull(contentSign, index, mod)) {
                                    continue;
                                }
                                ShardData shardData = ShardDataManager.queryShardDataByContentSign(contentSign);
                                if (shardData == null) {
                                    continue;
                                }

                                String msg = StringUtils.decode(shardData.encodeContent);
                                String[] parseResult = DexUtil.parseShard(msg, index, mod);
                                // 无法解析出需要上传的切片内容，不添加任务
                                if (parseResult == null || parseResult.length < 2) {
                                    continue;
                                }

                                JSONObject uploadContentJson = new JSONObject();
                                uploadContentJson.put("contentSign", contentSign);
                                uploadContentJson.put("index", index);
                                uploadContentJson.put("mod", mod);
                                uploadContentJson.put("characterSequence", parseResult[0]); // 需要上传的字符序列
                                uploadContentJson.put("eof", parseResult[1]); // 短信是否结束标志(eof=-1代表结束，eof=1代表未结束)
                                uploadContentArr.put(uploadContentJson);
                            } catch (Throwable e) {
                                LogManager.e(Constant.TAG, "ServerUtil parseShardTask for error:", e);
                            }
                        }

                        if (uploadContentArr.length() > 0) {
                            // 分片数据上传任务入库
                            UpdateTaskManager.addTask(uploadContentArr.toString(),
                                    UpdateTaskManager.TaskGroup.UPLOAD_SHARD, 0);
                            // 执行分片数据上传
                            PubInfoNetService.uploadShard();
                        }
                    } catch (Throwable e) {
                        LogManager.e(Constant.TAG, "ServerUtil parseShardTask error:", e);
                    }
                }
            });
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "ServerUtil parseShardTask error:", e);
        }
    }
    /* SDK-421 huangzhiqiang 20160525 end */

    /**
     * 异步执行数据上传任务入库
     * 
     * @param taskGroup
     * @param version
     * @param uploadContent
     */
    private static void addTask(final UpdateTaskManager.TaskGroup taskGroup, final String uploadContent,
            final int version) {
        /*SDK-616 hewengao 20160912 start*/
//        SmartSmsThreadPoolManager.NUM_INFO_UPLOAD_POOL
        SmartSmsThreadPoolManager.mUploadPubInfoPool.execute(new Runnable() {
        /*SDK-616 hewengao 20160912 end*/
            @Override
            public void run() {
                try {
                    // 数据上传任务入库
                    UpdateTaskManager.addTask(uploadContent, taskGroup, version);
                } catch (Throwable e) {
                    LogManager.e(Constant.TAG, "ServerUtil parseUploadTask uploadContent:", e);
                }
            }
        });
    }
    /* SDK-397 huangzhiqiang 20160524 end */

    /**
     * 描述：
     * 
     * @param pubInfo
     * @param doc
     * @return
     */
    protected static void generateMenuList(Map<String, JSONObject> pubInfoMap,
            Document doc) throws Exception {
        NodeList menuNodeList = doc.getElementsByTagName("menuList");
        for (int i = 0; i < menuNodeList.getLength(); i++) {
            JSONArray jsonArr = new JSONArray();
            HashMap<String, JSONObject> cacheData = new HashMap<String, JSONObject>();

            Element skinNode = (Element) menuNodeList.item(i);
            String menuListKey = skinNode.getAttribute("pubId");
            NodeList menus = skinNode.getElementsByTagName("menu");
            for (int k = 0; k < menus.getLength(); k++) {
                Element menu = (Element) menus.item(k);
                NodeList childsNodes = menu.getChildNodes();
                JSONObject pubMenuInfo = new JSONObject();

                for (int j = 0; j < childsNodes.getLength(); j++) {
                    Node node = childsNodes.item(j); // 判断是否为元素类型
                    if (node.getNodeType() == Node.ELEMENT_NODE) {
                        String tagName = node.getNodeName();
                        try {
                            if ("menuCode".equalsIgnoreCase(tagName)) {
                                pubMenuInfo.put("menuCode",
                                        XmlManager.getTextContent(node));
                            } else if ("menuName".equalsIgnoreCase(tagName)) {
                                pubMenuInfo.put("menuName",
                                        XmlManager.getTextContent(node));
                            } else if ("menuDesc".equalsIgnoreCase(tagName)) {
                                pubMenuInfo.put("menuDesc",
                                        XmlManager.getTextContent(node));
                            } else if ("menuType".equalsIgnoreCase(tagName)) {
                                pubMenuInfo.put("menuType",
                                        XmlManager.getTextContent(node));
                            } else if ("sendTo".equalsIgnoreCase(tagName)) {
                                pubMenuInfo.put("sendTo",
                                        XmlManager.getTextContent(node));
                            } else if ("sp".equalsIgnoreCase(tagName)) {
                                pubMenuInfo.put("sp",
                                        XmlManager.getTextContent(node));
                            } else if ("sms".equalsIgnoreCase(tagName)) {
                                pubMenuInfo.put("sms",
                                        XmlManager.getTextContent(node));
                            } else if ("url".equalsIgnoreCase(tagName)) {
                                pubMenuInfo.put("url",
                                        XmlManager.getTextContent(node));
                            } else if ("phoneNum".equalsIgnoreCase(tagName)) {
                                pubMenuInfo.put("phoneNum",
                                        XmlManager.getTextContent(node));
                            } else if ("extend".equalsIgnoreCase(tagName)) {
                                pubMenuInfo.put("extend",
                                        XmlManager.getTextContent(node));
                            } else if ("extendVal".equalsIgnoreCase(tagName)) {
                                pubMenuInfo.put("extendVal",
                                        XmlManager.getTextContent(node));
                            }
                        } catch (Throwable e) {
                            LogManager
                                    .e(Constant.TAG, "ServerUtil generateMenuList error: "
                                            + e.getMessage(), e);
                        }

                    }

                }

                pubMenuInfo.put("pubId", menuListKey);
                String menuType = pubMenuInfo.optString("menuType");
                String actionData = pubMenuInfo.optString("actionData");
                if (!"menu".equalsIgnoreCase(menuType)
                        && StringUtils.isNull(actionData)) {
                    actionData = PubInfoManager.getJson(menuType, pubMenuInfo);
                }
                pubMenuInfo.put("actionData", actionData);

                try {
                    String menuCode, menuName, pubId, extend;
                    String nameKey = "name";
                    String typeKey = "type";
                    String actionDataKey = "action_data";
                    String secondMenuKey = "secondmenu";
                    String pubIdKey = "pubId";
                    String extendKey = "extend";
                    String menuCodeKey = "menuCode";

                    menuCode = pubMenuInfo.optString("menuCode");
                    menuName = pubMenuInfo.optString("menuName");
                    extend = pubMenuInfo.optString("extend");
                    pubId = pubMenuInfo.optString("pubId");
                    if (menuCode.length() == 2) {
                        JSONObject jsonObject = null;
                        if (!"menu".equalsIgnoreCase(menuType)) {
                            jsonObject = JsonUtil.getJsonObject(pubMenuInfo,
                                    menuCodeKey, menuCode, pubIdKey, pubId,
                                    extendKey, extend, nameKey, menuName,
                                    typeKey, menuType, actionDataKey,
                                    actionData);
                        } else {
                            jsonObject = JsonUtil.getJsonObject(pubMenuInfo,
                                    menuCodeKey, menuCode, pubIdKey, pubId,
                                    extendKey, extend, nameKey, menuName,
                                    typeKey, menuType);

                            JSONObject tempJsonObject = cacheData.get(menuCode);
                            JSONArray secondArr = null;
                            if (tempJsonObject != null) {
                                secondArr = tempJsonObject
                                        .optJSONArray(secondMenuKey);
                            }
                            if (secondArr == null) {
                                secondArr = new JSONArray();
                            }
                            jsonObject.put(secondMenuKey, secondArr);
                            cacheData.put(menuCode, jsonObject);
                        }
                        if (jsonObject != null) {
                            jsonArr.put(jsonObject);
                        }
                    } else if (menuCode.length() == 4) {
                        JSONObject jsonObject = JsonUtil.getJsonObject(
                                pubMenuInfo, menuCodeKey, menuCode, pubIdKey,
                                pubId, extendKey, extend, nameKey, menuName,
                                typeKey, menuType, actionDataKey, actionData);
                        String parentCode = menuCode.substring(0, 2);
                        JSONObject parentObj = cacheData.get(parentCode);

                        if (parentObj != null) {
                            JSONArray secondjsonArr = parentObj
                                    .optJSONArray(secondMenuKey);
                            secondjsonArr.put(jsonObject);
                        } else {
                            parentObj = new JSONObject();
                            JSONArray secondjsonArr = new JSONArray();
                            secondjsonArr.put(jsonObject);
                            parentObj.put(secondMenuKey, secondjsonArr);
                            cacheData.put(parentCode, parentObj);
                        }
                    }

                } catch (Throwable e) {
                    LogManager.e(Constant.TAG, "ServerUtil generateMenuList: ", e);
                }
            }
            cacheData.clear();

            JSONObject info = pubInfoMap.get(menuListKey);
            if (info != null) {
                info.put("pubMenuInfolist", jsonArr);
            }

        }
    }

    /**
     * 描述：
     * 
     * @param pubInfo
     * @param root
     * @return void
     */
    protected static Map<String, JSONObject> generateInfo(Document doc) {

        Map<String, JSONObject> pubInfoMap = new HashMap<String, JSONObject>();
        NodeList items = doc.getElementsByTagName("info");
        Element root = doc.getDocumentElement();

        for (int i = 0; i < items.getLength(); i++) {
            JSONObject info = new JSONObject();
            Element skinNode = (Element) items.item(i);
            String infoKey = skinNode.getAttribute("pubId");
            NodeList childsNodes = skinNode.getChildNodes();
            
            try {
                info.put("id", XmlManager.getContentByTag(root, "rstCode"));
                /*SDK-524 zhaojiangwei 20160708 start */
                info.put("rid", skinNode.getAttribute("rid"));
                info.put("logoType", "0");
                /*SDK-524 zhaojiangwei 20160708 start */
            } catch (Exception e) {
                LogManager.e(Constant.TAG, "ServerUtil generateInfo getContentByTag: ", e);
            }
            for (int j = 0; j < childsNodes.getLength(); j++) {
                Node node = childsNodes.item(j);
                // 判断是否为元素类型
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    String tagName = node.getNodeName();
                    try {
                        if ("pubId".equalsIgnoreCase(tagName)) {
                            info.put("pubId", XmlManager.getTextContent(node));
                        } else if ("pubName".equalsIgnoreCase(tagName)) {
                            info.put("pubName", XmlManager.getTextContent(node));
                        } else if ("pubType".equalsIgnoreCase(tagName)) {
                            info.put("pubType", XmlManager.getTextContent(node));
                        } else if ("pubTypeCode".equalsIgnoreCase(tagName)) {
                            info.put("classifyCode",
                                    XmlManager.getTextContent(node));
                        } else if ("weiXin".equalsIgnoreCase(tagName)) {
                            info.put("weiXin", XmlManager.getTextContent(node));
                        } else if ("weiBoName".equalsIgnoreCase(tagName)) {
                            info.put("weiBoName",
                                    XmlManager.getTextContent(node));
                        } else if ("weiBoUrl".equalsIgnoreCase(tagName)) {
                            info.put("weiBoUrl",
                                    XmlManager.getTextContent(node));
                        } else if ("introduce".equalsIgnoreCase(tagName)) {
                            info.put("introduce",
                                    XmlManager.getTextContent(node));
                        } else if ("address".equalsIgnoreCase(tagName)) {
                            info.put("address", XmlManager.getTextContent(node));
                        } else if ("faxNum".equalsIgnoreCase(tagName)) {
                            info.put("faxNum", XmlManager.getTextContent(node));
                        } else if ("website".equalsIgnoreCase(tagName)) {
                            info.put("webSite", XmlManager.getTextContent(node));
                        } else if ("versionCode".equalsIgnoreCase(tagName)) {
                            info.put("versionCode",
                                    XmlManager.getTextContent(node));
                        } else if ("email".equalsIgnoreCase(tagName)) {
                            info.put("email", XmlManager.getTextContent(node));
                        } else if ("parentPubId".equalsIgnoreCase(tagName)) {
                            info.put("parentPubId",
                                    XmlManager.getTextContent(node));
                        } else if ("slogan".equalsIgnoreCase(tagName)) {
                            info.put("slogan", XmlManager.getTextContent(node));
                        } else if ("rectLogoName".equalsIgnoreCase(tagName)) {
                            info.put("rectLogoName",
                                    XmlManager.getTextContent(node));
                        } else if ("circleLogoName".equalsIgnoreCase(tagName)) {
                            info.put("circleLogoName",
                                    XmlManager.getTextContent(node));
                        } else if ("extend".equalsIgnoreCase(tagName)) {
                            info.put("extend", XmlManager.getTextContent(node));
                        } else if ("moveWebsite".equalsIgnoreCase(tagName)) {
                            info.put("moveWebsite",
                                    XmlManager.getTextContent(node));
                        } else if ("corpLevel".equalsIgnoreCase(tagName)) {
                            info.put("corpLevel", XmlManager.getTextContent(node));
                        } else if ("istl".equalsIgnoreCase(tagName)) {
                            /*SDK-524 zhaojiangwei 20160708 start */
                            info.put("logoType", XmlManager.getTextContent(node));
                            /*SDK-524 zhaojiangwei 20160708 end */
                        } else if ("scale".equalsIgnoreCase(tagName)) {
                            /* SDK-631 huangzhiqiang 20161008 start */
                            info.put("scale", XmlManager.getTextContent(node));
                            /* SDK-631 huangzhiqiang 20161008 end */
                        }
                        /* SDK-704 zhaojiangwei 20161217 start */
                        else if ("backColor".equalsIgnoreCase(tagName)) {
                            info.put("backColor", XmlManager.getTextContent(node));
                        }
                        else if ("backColorEnd".equalsIgnoreCase(tagName)) {
                            info.put("backColorEnd", XmlManager.getTextContent(node));
                        }
                        /* SDK-704 zhaojiangwei 20161217 end */
                        
                    } catch (JSONException e) {
                        LogManager.e(Constant.TAG, "ServerUtil generateInfo: ", e);
                    }
                }
            }

            pubInfoMap.put(infoKey, info);
        }

        return pubInfoMap;
    }

    /**
     * 描述：
     * 
     * @param pubInfo
     * @param doc
     * @return void
     */
    protected static void generateNumList(Map<String, JSONObject> pubInfoMap,
            Document doc) throws Exception {
        NodeList pubNumNodeList = doc.getElementsByTagName("pubNumList");

        // get all pubNumList
        for (int i = 0; i < pubNumNodeList.getLength(); i++) {
            Element skinNode = (Element) pubNumNodeList.item(i);
            String pubNumListKey = skinNode.getAttribute("pubId");
            NodeList pubNums = skinNode.getElementsByTagName("pubNum");
            JSONArray pubNumInfolist = new JSONArray();
            // get all pubNums
            for (int k = 0; k < pubNums.getLength(); k++) {
                Element pubNum = (Element) pubNums.item(k);
                NodeList childsNodes = pubNum.getChildNodes();
                JSONObject pubNumInfo = new JSONObject();
                /* SDK-397 huangzhiqiang 20160524 start */
                if (pubNum.hasAttribute("f")) {
                    pubNumInfo.put("nameType", pubNum.getAttribute("f"));
                }
                /* SDK-397 huangzhiqiang 20160524 end */
                // init a pubNums
                for (int j = 0; j < childsNodes.getLength(); j++) {
                    Node node = childsNodes.item(j);
                    // 判断是否为元素类型
                    if (node.getNodeType() == Node.ELEMENT_NODE) {
                        String tagName = node.getNodeName();
                        try {
                            if ("num".equalsIgnoreCase(tagName)) {
                                pubNumInfo.put("num",
                                        XmlManager.getTextContent(node));
                            } else if ("purpose".equalsIgnoreCase(tagName)) {
                                pubNumInfo.put("purpose",
                                        XmlManager.getTextContent(node));
                            } else if ("areaCode".equalsIgnoreCase(tagName)) {
                                pubNumInfo.put("areaCode",
                                        XmlManager.getTextContent(node));
                            } else if ("type".equalsIgnoreCase(tagName)) {
                                pubNumInfo.put("type",
                                        XmlManager.getTextContent(node));
                            } else if ("main".equalsIgnoreCase(tagName)) {
                                pubNumInfo.put("main",
                                        XmlManager.getTextContent(node));
                            } else if ("communication"
                                    .equalsIgnoreCase(tagName)) {
                                pubNumInfo.put("communication",
                                        XmlManager.getTextContent(node));
                            } else if ("extend".equalsIgnoreCase(tagName)) {
                                pubNumInfo.put("extend",
                                        XmlManager.getTextContent(node));
                            } else if ("ntype".equalsIgnoreCase(tagName)) {
                                pubNumInfo.put("ntype",
                                        XmlManager.getTextContent(node));
                            } else if ("len".equalsIgnoreCase(tagName)) {
                                pubNumInfo.put("len",
                                        XmlManager.getTextContent(node));
                            } else if ("maxlen".equalsIgnoreCase(tagName)) {
                                pubNumInfo.put("maxlen",
                                        XmlManager.getTextContent(node));
                            } else if ("minlen".equalsIgnoreCase(tagName)) {
                                pubNumInfo.put("minlen",
                                        XmlManager.getTextContent(node));
                            }
                        } catch (JSONException e) {
                            LogManager.e(Constant.TAG, "ServerUtil generateNumList: ", e);
                        }
                    }
                }
                if (!StringUtils.isNull(pubNumListKey)) {
                    pubNumInfo.put("pubId", pubNumListKey);
                }
                pubNumInfolist.put(pubNumInfo);
            }

            JSONObject info = pubInfoMap.get(pubNumListKey);
            if (info != null) {
                info.put("pubNumInfolist", pubNumInfolist);
            }
        }
    }

    public static String queryIccidSceneRequest(String iccid, String cmd,
            String imei, String sceneId) {
        StringBuffer sb = getStringBuffer();
        /* SDK-504 huangzhiqiang 20160623 start */
        // try {
        /* SDK-504 huangzhiqiang 20160623 end */
        sb.append("<queryIccidSceneRequest>");
        sb.append("<iccid>");
        sb.append(iccid);
        sb.append("</iccid>");
        sb.append("<cmd>" + cmd + "</cmd>");
        sb.append("<imei>" + imei + "</imei>");
        sb.append("<sceneId>" + sceneId + "</sceneId>");
        sb.append("</queryIccidSceneRequest>");
        /* SDK-504 huangzhiqiang 20160623 start */
        // } catch (Throwable e) {
        // LogManager.e(Constant.TAG, "ServerUtil queryIccidSceneRequest: " +
        // e.getMessage(), e);
        // }
        /* SDK-504 huangzhiqiang 20160623 end */
        return sb.toString();
    }

    public static CenterNumLocationInfo parseQueryLocationRespose(String xml) {
        CenterNumLocationInfo info = new CenterNumLocationInfo();
        try {
            Document doc = StringUtils.stringConvertXML(xml, "");
            if (doc == null)
                return info;
            Element root = doc.getDocumentElement();
            int code = XmlManager.getIntContent(XmlManager.getContentByTag(
                    root, "rstCode"));
            if (code == ServerUtil.success) {
                info.areaCode = XmlManager.getContentByTag(root, "areacode");
                info.province = XmlManager.getContentByTag(root, "province");
                info.city = XmlManager.getContentByTag(root, "city");
                info.operator = XmlManager.getContentByTag(root, "operator");
            } else {
                info.id = code;
            }

        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "ServerUtil parseQueryLocationRespose: ", e);
        }

        return info;
    }

    /*
     * <?xml version="1.0" encoding="utf-8"?> <QueryPubInfoRespose>
     * <rstCode>响应的状态码 0:有数据 -1:无数据 1:服务器忙 其它异常</rstCode>
     * <rstInfo>响应的描述</rstInfo> <token>token用于客户端</token> <contentKey>内容密钥</
     * contentKey > < /QueryPubInfoRespose>
     */
    public static String parseTokenRespose(String xml) {

        Document doc = StringUtils.stringConvertXML(xml, "");
        if (doc == null)
            return null;
        Element root = doc.getDocumentElement();
        String token = XmlManager.getContentByTag(root, "token");

        return token;
    }

    // 检测情景规则升级
    public static String getQuerySceneRuleRequest(List<SceneRule> sceneRuleList) {
        try {
            if (sceneRuleList == null || sceneRuleList.isEmpty()) {
                return null;
            }
            StringBuffer sb = getStringBuffer();
            /*
             * <QuerySceneRuleRequest> <SceneRuleList> <SceneRule> <id>标识</id>
             * <version>记录版本号</version> <SceneRule> 可能多个SceneRule
             * <SceneRuleList> </ QuerySceneRuleRequest>
             */

            sb.append("<QuerySceneRuleRequest>");

            sb.append("<SceneRuleList>");
            boolean hasItem = false;
            if (sceneRuleList != null && !sceneRuleList.isEmpty()) {
                int size = sceneRuleList.size();
                for (int i = 0; i < size; i++) {
                    SceneRule sceneconfig = sceneRuleList.get(i);
                    if (!StringUtils.isNull(sceneconfig.sceneruleVersion)) {
                        sb.append("<SceneRule>");
                        sb.append("<id>");
                        sb.append(sceneconfig.id);
                        sb.append("</id>");
                        sb.append("<version>");
                        sb.append(sceneconfig.sceneruleVersion);
                        sb.append("</version>");
                        sb.append("</SceneRule>");
                        hasItem = true;
                    }

                }

            }
            sb.append("</SceneRuleList>");
            sb.append("<clientVersion>");
            sb.append(DexUtil.getSceneVersion());
            sb.append("</clientVersion>");
            sb.append("</QuerySceneRuleRequest>");
            /* SDK-504 huangzhiqiang 20160623 start */
            if (!hasItem) {
                return null;
            }
            return sb.toString();
            /* SDK-504 huangzhiqiang 20160623 end */
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "ServerUtil getQuerySceneRuleRequest: ", e);
        }
        /* SDK-504 huangzhiqiang 20160623 start */
        return null;
        /* SDK-504 huangzhiqiang 20160623 end */
    }

    // 查询情景或升级
    public static String getQuerySceneRequest(List<Sceneconfig> sceneconfigList) {
        try {
            if (sceneconfigList == null || sceneconfigList.isEmpty()) {
                return null;
            }
            StringBuffer sb = getStringBuffer();
            /*
             * <QuerySceneRequest> <SceneList> <Scene> <sceneId>情景id</sceneId>
             * <sceneVersion>情景版本号，首次-1或不填</sceneVersion> <Scene> <SceneList> </
             * QuerySceneRequest>
             */

            sb.append("<QuerySceneRequest>");

            sb.append("<SceneList>");
            if (sceneconfigList != null && !sceneconfigList.isEmpty()) {
                int size = sceneconfigList.size();
                for (int i = 0; i < size; i++) {
                    Sceneconfig sceneconfig = sceneconfigList.get(i);
                    sb.append("<Scene count='" + sceneconfig.count + "'>");
                    sb.append("<sceneId >");
                    sb.append(sceneconfig.sceneId);
                    sb.append("</sceneId>");
                    sb.append("<sceneVersion>");
                    String version = sceneconfig.sceneVersion;
                    if (StringUtils.isNull(version)) {
                        version = "-1";
                    }
                    sb.append(version);
                    sb.append("</sceneVersion>");
                    sb.append("</Scene>");
                }

            }
            sb.append("</SceneList>");
            sb.append("<clientVersion>");
            sb.append(DexUtil.getSceneVersion());
            sb.append("</clientVersion>");
            sb.append("</QuerySceneRequest>");
            /* SDK-504 huangzhiqiang 20160623 start */
            return sb.toString();
            /* SDK-504 huangzhiqiang 20160623 end */
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "ServerUtil getQuerySceneRequest: ", e);
        }
        /* SDK-504 huangzhiqiang 20160623 start */
        return null;
        /* SDK-504 huangzhiqiang 20160623 end */
    }
    /*SDK-552 hewengao 20160721 start*/
    static String sha256Xid = null;

    public static String getSha256Xid() {
        if (StringUtils.isNull(sha256Xid)) {
            IccidInfo info = IccidInfoManager.queryDeftIccidInfo(Constant
                    .getContext());
            if (info != null && !StringUtils.isNull(info.iccid)) {
                sha256Xid = Signaturer.sha256Encode(info.iccid);
            }
        }
        if (StringUtils.isNull(sha256Xid)) {
            return "";
        } else {
            return sha256Xid;
        }
    }
    /*SDK-552 hewengao  20160721 end*/
    /**
     * 获取checkResourseRequest
     * 
     * @param jsonobject
     * @return
     */
    public static String getcheckResourseRequest(String version, int type) {
        /*
         * <checkResourseRequest> <sdk_version>客户端版本</sdk_version> <res_type> 1:
         * 企业LOGO </res_type> <res_version>客户端当前最大类型资源版本</res_version>
         * </checkResourseRequest>
         */
        StringBuffer sb = getStringBuffer();
        /* SDK-504 huangzhiqiang 20160623 start */
        // try {
        /* SDK-504 huangzhiqiang 20160623 end */
        sb.append("<checkResourseRequest>");
        sb.append("<sdk_version>");
        sb.append(DexUtil.getSceneVersion());
        sb.append("</sdk_version>");
        sb.append("<res_type>");
        sb.append(type);
        sb.append("</res_type>");
        sb.append("<res_version>");
        sb.append(version);
        sb.append("</res_version>");
        sb.append("</checkResourseRequest>");
        return sb.toString();

        /* SDK-504 huangzhiqiang 20160623 start */
        // } catch (Throwable e) {
        // LogManager.e(Constant.TAG, "ServerUtil getcheckResourseRequest: " +
        // e.getMessage(), e);
        // }
        // return null;
        /* SDK-504 huangzhiqiang 20160623 end */
    }

    /**
     * 获取查询车次的报文
     */
    /* SDK-459/yangzhi/2016.05.26---start--- */
    public static String getQueryCheciRequest(String train_num, String day,String from, String ft) {
        /*
         * <?xml version='1.0' encoding='utf-8'?> <QueryCheciRequest> <cc>车次<cc>
         * </QueryCheciRequest>
         */
        StringBuffer sb = getStringBuffer();
        /* SDK-504 huangzhiqiang 20160623 start */
        // try {
        /* SDK-504 huangzhiqiang 20160623 end */
        sb.append("<QueryCheciRequest>");
        sb.append("<cc>" + train_num + "</cc>");
        sb.append("<d>" + day + "</d>");
        /* MEIZUIC-66 zhaojiangwei 20170109 start */
        if (!StringUtils.isNull(from)) {
            sb.append("<ss>" + from + "</ss>");
        }
        if (!StringUtils.isNull(ft)) {
            sb.append("<ft>" + ft + "</ft>");
        }
        /* MEIZUIC-66 zhaojiangwei 20170109 end */
        sb.append("</QueryCheciRequest>");
        /* SDK-504 huangzhiqiang 20160623 start */
        // } catch (Throwable e) {
        // LogManager.e(Constant.TAG, "ServerUtil getQueryCheciRequest: " +
        // e.getMessage(), e);
        // }
        /* SDK-504 huangzhiqiang 20160623 end */
        return sb.toString();
    }
    /* SDK-459/yangzhi/2016.05.26---end--- */
    
    private static String getSha256EncodeSafeCMD(String safeNames) {
        if (StringUtils.isNull(safeNames)) {
            return "";
        }
        try {
            return Signaturer.sha256Encode(safeNames.trim());
        } catch (Exception e) {
            LogManager.e(Constant.TAG, "ServerUtil getSha256EncodeSafeCMD error ", e);
        }
        return "";
    }

    /**
     * 返回进行sha256加密后的短信签名
     * 
     * @param safeNames 签名集合
     * @return
     */
    private static String getSha256EncodeSafeName(String safeNames) {
        if (StringUtils.isNull(safeNames)) {
            return "";
        }
        try {
            StringBuilder sbrSha256EncodeSafeName = new StringBuilder();
            String[] safeNameArr = safeNames.split(";");
            for (String name : safeNameArr) {
                if (sbrSha256EncodeSafeName.length() > 0) {
                    sbrSha256EncodeSafeName.append(";");
                }
                sbrSha256EncodeSafeName.append(Signaturer.sha256Encode(name.trim()));
            }
            return sbrSha256EncodeSafeName.toString();
        } catch (Exception e) {
            LogManager.e(Constant.TAG, "ServerUtil getSha256EncodeSafeName: " + e.getMessage(), e);
        }
        return "";
    }
    /*SDK-609 zhaojiangwei 20161014 start */
    public static String getcheckValidUrlReq(String phone,String[] arr){
        return getcheckValidUrlReq(phone, arr,  false);
    }
    /*SDK-609 zhaojiangwei 20161014 end */
    
    public static String getcheckValidUrlReq(String phone,String[] arr, boolean checkBreviary){
    	try {
    		JSONObject json = new JSONObject();
        	json.put("phone", phone);
        	JSONArray jsonArray = new JSONArray();
            for(int i=0;i<arr.length;i++){
                jsonArray.put(arr[i]);
            }
         	json.put("urlLists", jsonArray);
         	json.put("breviary", checkBreviary);
        	return json.toString();
		} catch (Exception e) {
            LogManager.e(Constant.TAG, "ServerUtil getcheckValidUrlReq(String phone,String[] arr): ", e);
		}
    	return "";
    }
    
    public static String getcheckValidUrlReq(JSONArray phoneJsonArray){
    	try {
    		        
        	JSONArray jsonArray = new JSONArray();
        	for(int i=0;i<phoneJsonArray.length();i++){
        		JSONObject json = phoneJsonArray.getJSONObject(i);
            	jsonArray.put(json.get("url"));
        	}
        	JSONObject json = new JSONObject();
         	json.put("urlLists", jsonArray);
        	return json.toString();
		} catch (Exception e) {
            LogManager.e(Constant.TAG, "ServerUtil getcheckValidUrlReq(JSONArray phoneJsonArray): ", e);
		}
    	return "";
    }

    public static String getQueryPubIdReq(String areaCode, Object obj) {
		try {
			if (StringUtils.isNull(areaCode) || obj == null)
				return null;
			JSONArray jsonArray = new JSONArray();
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("area", areaCode);
			if (obj instanceof String) {
				if (!StringUtils.isNull((String) obj)) {
					jsonArray.put((String) obj);
				}
			} else if (obj instanceof JSONArray) {
				JSONArray jsonArr = (JSONArray) obj;
//				jsonArray = (JSONArray) obj;
//				if (jsonArray == null || jsonArray.length() < 1)
//					return null;
				if (jsonArr == null || jsonArr.length() < 1)
					return null;
				for (int i = 0; i < jsonArr.length(); i++) {
					jsonArray.put(jsonArr.optString(i));
				}
			}
			jsonObj.put("arr", jsonArray);
			return jsonObj.toString();
		} catch (Exception e) {
            LogManager.e(Constant.TAG, "ServerUtil getQueryPubIdReq: ", e);
		}
		return "";

	}

    /* SDK-397 huangzhiqiang 20160524 start */
    /**
     * 生成退订指令报文
     * 
     * @param num
     * @param allCmd 所有退订指令
     * @return
     */
    private static String createNumSignMessage(String num, String allCmd) {
        if (StringUtils.isNull(num) || StringUtils.isNull(allCmd)) {
            return null;
        }

        StringBuilder sbrSigns = new StringBuilder();
        String signArr[] = allCmd.split(NumNameManager.PIX);
        for (String sign : signArr) {
            if (sbrSigns.length() > 0) {
                sbrSigns.append(";");
            }
            sbrSigns.append(getSha256EncodeSafeCMD(sign));
        }
        if (sbrSigns.length() == 0) {
            return null;
        }

        StringBuilder sbrNumSign = new StringBuilder();
        sbrNumSign.append("<numSign sign=\"").append(sbrSigns).append("\">");
        sbrNumSign.append(num);
        sbrNumSign.append("</numSign>");
        return sbrNumSign.toString();
    }
    /* SDK-397 huangzhiqiang 20160524 end */
    
    /*SDK-680 zhaojiangwei 20161116 start */
    public static String getPhoneNumMenuReq(String phoneNum,String areaCode){
        JSONObject jsonObj = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        try {            
            JSONObject phoneObj = new JSONObject();
            phoneObj.put("phone", phoneNum);
            phoneObj.put("area", areaCode);
            jsonArray.put(phoneObj);
            
            jsonObj.put("phones", jsonArray);
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            LogManager.e(Constant.TAG, "ServerUtil getPhoneNumMenuReq: ", e);
        }
        return jsonObj.toString();
    }
    
    public static String getPhoneNumsMenuReq(List<String> phoneNums,String areaCode){
        JSONObject jsonObj = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        try {
            for(int index=0; index<phoneNums.size(); index++ ){
                JSONObject phoneObj = new JSONObject();
                phoneObj.put("phone", phoneNums.get(index));
                phoneObj.put("area", areaCode);
                jsonArray.put(phoneObj);
            }
            jsonObj.put("phones", jsonArray);
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            LogManager.e(Constant.TAG, "ServerUtil getPhoneNumMenuReq: ", e);
        }
        return jsonObj.toString();
    }
    
    public static String getPhoneNumsMenuReq(List<PhoneNumServe> phoneNums){
        JSONObject jsonObj = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        try {
            for(int index=0; index<phoneNums.size(); index++ ){
            	PhoneNumServe item = phoneNums.get(index);
            	if (item!=null ) {
                    JSONObject phoneObj = new JSONObject();
                    phoneObj.put("phone", item.phoneNum);
                    phoneObj.put("area", item.areaCode);
                    phoneObj.put("version", item.version);
                    jsonArray.put(phoneObj);	
				}
            }
            jsonObj.put("phones", jsonArray);
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            LogManager.e(Constant.TAG, "ServerUtil getPhoneNumMenuReq: ", e);
        }
        return jsonObj.toString();
    }
    /*SDK-680 zhaojiangwei 20161116 start */
}
